<template>
  <div class="app-container">
    <div class="table_container">
      <div class="table_top_btn">
        <div class="left_btn">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="openAddOrEdit('add', info)"
            >{{ t("button.add") }}</el-button
          >
          <exportButton
            :columns="columns"
            :data="assetsData"
            :filename="`${t('assetsList.assetDetails')}(${getNowDate()})`"
          ></exportButton>
          <el-button
            :disabled="assetsSelection.length == 0 ? true : false"
            type="success"
            plain
            icon="Printer"
            @click="openPrinter('add', info)"
            >{{ t("button.print") }}</el-button
          >

          <AshUpload
            v-if="uploadVisible"
            :file-type="'.xls,.xlsx'"
            :btnText="`
         ${t('asset.assetInitialization')}`"
            :file-size="0.1"
            :limit="1"
            :multiple="false"
            :tip-show="false"
            @upload-success="UploadAssets"
          />

          <el-button type="primary" plain icon="Download" @click="DownLoadAsstesTemp">
            {{ t("button.downloadImportTemplate") }}</el-button
          >
        </div>
        <right-toolbar
          ref="rightToolRef"
          @queryTable="queryList"
          v-model:searchConfig="searchConfig"
          :columns="columns"
          @search="handleSearch"
        >
        </right-toolbar>
      </div>
      <div class="table_area">
        <el-table
          ref="assetsTableRef"
          height="100%"
          v-loading="loading"
          :data="assetsData"
          :header-cell-style="{ textAlign: 'center' }"
          @selection-change="handleToPrint"
          @row-click="handleRowChick"
          :row-class-name="getRowClass"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            :label="t('tableColumns.operation')"
            align="center"
            fixed
            width="90"
          >
            <template #default="{ row }">
              <div class="operate_link_btn">
                <el-link
                  type="warning"
                  :underline="false"
                  :icon="Edit"
                  @click="openAddOrEdit('edit', row)"
                  :disabled="row.enableFlag == 99"
                  >{{ t("button.edit") }}</el-link
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="50"> </el-table-column>

          <template v-for="(item, index) in columns" :key="item.key">
            <el-table-column
              v-if="item.visible"
              :prop="item.prop"
              :label="t(`tableColumns.${item.langKey}`)"
              :width="item.width"
              :show-overflow-tooltip="true"
            >
              <template #default="{ row }">
                <el-tag
                  v-if="item.prop == 'enableFlag'"
                  :type="
                    row.enableFlag == 0
                      ? 'success'
                      : row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                      ? 'warning'
                      : 'danger'
                  "
                >
                  {{ row.enableFlagName }}
                </el-tag>
                <span v-else-if="item.prop == 'purchaseDate'">
                  {{ parseTime(row[item.prop], "{y}-{m}-{d} {h}:{i}:{s}") || "无" }}
                </span>
                <span
                  v-else-if="item.prop == 'assetsCode'"
                  :style="{
                    color: colors.primaryColor,
                    cursor: item.isclick ? 'pointer' : '',
                  }"
                  @click="openAddOrEdit('detail', row)"
                >
                  {{ row.assetsCode }}
                </span>

                <span v-else>{{ row[item.prop] || "无" }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="pagination-area">
        <pagination
          :total="page.total"
          v-model:page="page.pageNum"
          v-model:limit="page.pageSize"
          @pagination="queryList"
        />
      </div>
    </div>

    <!-- 添加或修改资产配置对话框 @filterUseUser="filterUseUser"  -->
    <addOrEditDialog
      v-if="operate.open"
      ref="addOrEditRef"
      :operate="operate"
      @organizeNodeClick="organizeNodeClick"
      @changeUnitId="changeUnitId"
      @submitAddOrEdit="submitAddOrEdit"
      @cancelAddOrEdit="cancelAddOrEdit"
    ></addOrEditDialog>

    <printerDialog
      v-if="printerForm.open"
      ref="printerRef"
      :operate="printerForm"
      @canle="canclePrint"
      @submitPrint="submitPrint"
    >
    </printerDialog>
  </div>
</template>

<script setup name="AssetisList">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
console.log(1111, t("tableColumns.assetsColums.enableFlag"));
import * as pdfjsLib from "pdfjs-dist";
// 设置 Worker 的路径
pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.mjs";
import colors from "@/assets/styles/variables.module.scss";
import { Edit, Download } from "@element-plus/icons-vue";
import addOrEditDialog from "./components/addOrEditDialog.vue";
import printerDialog from "./components/printerDialog.vue";
import exportButton from "@/components/file/exportButton";
import RightToolbar from "@/components/RightToolbar";
import AshUpload from "@/components/AshUpload";
import {
  GetAssetsList,
  AddOrEditAssets,
  GetPrinterTempList,
  PrintFasAssets,
  DownloadAssetsExcel,
  ImportAssets,
} from "@/api/assetsManage/assetsList";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { assetsColums } from "@/utils/table/columns";
const { proxy } = getCurrentInstance();
const { MeasurementUnit, AssetClassification, AssetSources, AssetStatus } = proxy.useDict(
  "MeasurementUnit",
  "AssetClassification",
  "AssetSources",
  "AssetStatus"
);
const { GeographicRegion } = proxy.useTreeDict("GeographicRegion");
const assetsStatus = computed(() => {
  const data = AssetStatus.value || []; // 防止 AssetStatus.value 为 null/undefined
  return [
    { id: -1, name: "全部" },
    ...data.map((item) => ({
      id: Number(item.itemValue),
      name: item.dictionaryName,
    })),
  ];
});
const assetsData = ref([]); //资产列表数据
const loading = ref(false);
const columns = assetsColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const info = reactive({
  assetsCode: "",
  assetsName: "",
  assetsClassifyId: "",
  ownershipOrganizationalId: "",
  storekeeperUserId: "",
  useOrganizationId: "",
  useUserId: "",
  regionId: "",
  assetsSourceId: "",
  storageLocation: "",
  specModel: "",
  unitId: "",
  assetsCost: "",
  serviceLife: "",
  purchaseDate: "",
  supplierName: "",
  manufacturerName: "",
  remark: "",
});
const operate = reactive({
  open: false,
  openKey: "",
  title: "",
  addLoading: false, //确认的按钮，需要防止重复提交
  FormInfo: {},
  rules: {
    assetsName: [
      {
        required: true,
        message: t("assetsList.assetsNameRuleErrorTip"),
        trigger: "blur",
      },
    ],
    assetsClassifyId: [
      {
        required: true,
        message: t("assetsList.assetsClassifyIdRuleErrorTip"),
        trigger: "change",
      },
    ],
    ownershipOrganizationalId: [
      {
        required: true,
        message: t("assetsList.ownershipOrganizationalIdRuleErrorTip"),
        trigger: "change",
      },
    ],
    regionId: [
      {
        required: true,
        message: t("assetsList.regionIdRuleErrorTip"),
        trigger: "change",
      },
    ],
    assetsSourceId: [
      {
        required: true,
        message: t("assetsList.assetsSourceIdRuleErrorTip"),
        trigger: "change",
      },
    ],
    unitId: [
      {
        required: true,
        message: t("assetsList.unitIdRuleErrorTip"),
        trigger: "change",
      },
    ],
    specModel: [
      {
        required: true,
        message: t("assetsList.specModelRuleErrorTip"),
        trigger: "blur",
      },
    ],
    assetsCost: [
      {
        required: true,
        message: t("assetsList.assetsCostRuleErrorTip"),
        trigger: "blur",
      },
    ],
  },
  loadingUser: false, //加载使用人员
  loadingCustodian: false, //加载保管人员
  useUserOptions: [], //使用人员列表
  storekeeperUserOptions: [], //保管人员列表
  assetsClassifyOptions: AssetClassification, //资产分类
  organizeOptions: [], //组织
  selectedOrganization: {}, //当前选中的组织
  areaOptions: GeographicRegion, //区域
  assetSourcesOptions: AssetSources, //资产来源
  unitOptions: MeasurementUnit,
});
const depts = ref([]);
const assetsSelection = ref([]); //选中
const assetsTableRef = ref(null); //表格dom

const addOrEditRef = ref(null);
const printerRef = ref(null);
const rightBtn = reactive({
  // 显隐列
  showSearch: true,
  drawerSearchVisible: false,
});
//打印的相关字段
const printerForm = reactive({
  open: false,
  title: "",
  addLoading: false, //确认的按钮，需要防止重复提交
  loadingTable: false, //加载数据
  printTempData: [], //选择模板后进行单选提交
});
const uploadParams = ref({
  operatingUserId: "",
  operatingUserName: "",
  assetFile: null,
});
const uploadVisible = ref(false);

//上传资产
async function UploadAssets(fileList) {
  const params = {
    operatingUserId: JSON.parse(getUserInfo()).userId,
    operatingUserName: JSON.parse(getUserInfo()).userName,
    assetFile: fileList,
  };
  try {
    const res = await ImportAssets(params);
    ElMessage({ message: t("message.importSuccess"), type: "success" });
    queryList();
  } catch (error) {
    console.error("上传失败", error);
    // ElMessage({ message: "暂无打印模板", type: "warning" });
  }
}

//下载导入模板
function DownLoadAsstesTemp() {
  DownloadAssetsExcel("/Interface/AssetFileCase", {}, "资产导入模板.xlsx", "GET");
}

///333打印
const openPrinter = async (key, row) => {
  printerForm.open = true;
  printerForm.title = t("assetsList.templateChoose");
  await queryPrinterTmp();
};
///获取打印模板
const queryPrinterTmp = (row) => {
  printerForm.loadingTable = true;
  const params = {
    reportTypeId: 0,
    systemId: import.meta.env.VITE_APP_SYS_ID,
  };
  GetPrinterTempList(params).then(
    (res) => {
      printerForm.loadingTable = false;
      printerForm.printTempData = res.output;

      // 如果模板只有一个，自动选中并提交
      if (printerForm.printTempData.length === 1) {
        nextTick(() => {
          if (printerRef.value) {
            printerRef.value.handleSingleRowClick(printerForm.printTempData[0]);
            setTimeout(() => {
              printerRef.value.submitPrint(); // 确保选中状态更新后再提交
            }, 300);
          }
        });
      }
      if (res.output.length == 0) {
        ElMessage({ message: t("assetsList.printTempEmpty"), type: "warning" });
      }
    },
    (err) => {
      printerForm.loadingTable = false;
      printerForm.printTempData = [];
    }
  );
};
const canclePrint = () => {
  printerForm.open = false;
};

const loadPdf = (dataStr) => {
  //转二进制
  const byteArray = new Uint8Array(
    atob(dataStr)
      .split("")
      .map((char) => char.charCodeAt(0))
  );
  const blob = new Blob([byteArray], { type: "application/pdf" });
  var date = new Date().getTime();
  var iframe = document.createElement("iframe");
  iframe.style.frameborder = "no";
  iframe.style.display = "none"; // 不显示 iframe
  iframe.style.pageBreakBefore = "always";
  iframe.setAttribute("id", "printPdf" + date);
  iframe.setAttribute("name", "printPdf" + date);
  // 创建临时的 URL
  iframe.src = window.URL.createObjectURL(blob);
  // 将 iframe 添加到 DOM 中
  document.body.appendChild(iframe);
  // 执行打印
  doPrint("printPdf" + date);
  // 打印完成后释放 URL 对象
  window.URL.revokeObjectURL(iframe.src);
};
const doPrint = (val) => {
  var ordonnance = document.getElementById(val).contentWindow;
  setTimeout(() => {
    ordonnance.print();
  }, 100);
};

const submitPrint = (reportId) => {
  printerForm.addLoading = true;
  const codes = assetsSelection.value.map((item) => item.assetsCode);
  const params = {
    userId: JSON.parse(getUserInfo()).userId,
    reportId: reportId.value,
    listCodeNo: codes,
  };

  PrintFasAssets(params).then(
    (res) => {
      printerForm.addLoading = false;
      ElMessage({ message: t("message.printSuccess"), type: "success" });
      loadPdf(res.output.imgBytes);
      printerForm.open = false;
    },
    (err) => {
      printerForm.addLoading = false;
      ElMessage({ message: t("message.printFailed"), type: "error" });
    }
  );
};

//1111获取列表
const queryList = () => {
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...searchConfig.value.form,
  };
  params.enableFlag ? params.enableFlag : -1;
  params.IsCheck ? params.IsCheck : -1;

  loading.value = true;
  GetAssetsList(params)
    .then((res) => {
      loading.value = false;
      uploadVisible.value = !res.output.UniversalState; // 设置 uploadVisible 为 false
      assetsData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};

//组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      operate.organizeOptions = res.output;
      depts.value = res.output;
    })
    .catch((err) => {
      console.log("组织获取失败", err);
    });
};
const organizeNodeClick = (node, key) => {
  operate.selectedOrganization = node;
  if (key == "useOrganization") {
    operate.FormInfo.useUserId = "";
    queryAllUsers(operate.selectedOrganization.value);
  } else {
    operate.FormInfo.storekeeperUserId = "";
    queryStrokeUser(operate.selectedOrganization.value);
  }
};

//保管人员
const queryStrokeUser = (organizeId) => {
  operate.loadingCustodian = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      operate.storekeeperUserOptions = res.output;
      operate.loadingCustodian = false;
    })
    .catch((err) => {
      operate.storekeeperUserOptions = [];
      operate.loadingCustodian = false;
    });
};
//使用人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      operate.useUserOptions = res.output;

      operate.loadingUser = false;
    })
    .catch((err) => {
      operate.useUserOptions = [];
      operate.loadingUser = false;
    });
};
const handleToPrint = (e) => {
  assetsSelection.value = e;
};
const handleRowChick = (row, column) => {
  console.log(column);
  //阻止行内点击与操作按钮点击冲突，希望点击按钮不会变色/选中
  if (column && column.label == t("tableColumns.operation")) {
    return;
  }
  const selected = assetsSelection.value.some((item) => item.assetsId === row.assetsId);
  if (!selected) {
    assetsSelection.value.push(row);
    assetsTableRef.value.toggleRowSelection(row);
  } else {
    const finArr = assetsSelection.value.filter((item) => {
      return item.assetsId !== row.assetsId;
    });
    assetsSelection.value = finArr;
    assetsTableRef.value.toggleRowSelection(row, false);
  }
};
//点击高亮
const getRowClass = ({ row }) => {
  return proxy.rowClass(row, assetsSelection.value, "assetsId");
};
//解决高级搜索里响应式问题
const users = computed(() => {
  return operate.useUserOptions;
});

//222添加修改相关
const openAddOrEdit = (key, row) => {
  operate.open = true;
  operate.title =
    key == "add"
      ? t("assetsList.addAssetsDialogTitle")
      : key == "edit"
      ? t("assetsList.editAssetsDialogTitle")
      : t("assetsList.viewAssetsDialogTitle");
  operate.openKey = key;
  operate.addLoading = false;
  operate.FormInfo = JSON.parse(JSON.stringify(row));
  operate.organizeOptions = depts.value;
};

const changeUnitId = (selectedUnitId) => {
  //根据id 查找返回出对象
  const selectedUnit = operate.unitOptions.find(
    (item) => item.dictionaryCode === selectedUnitId
  );
  if (selectedUnit) {
    operate.FormInfo.unit = selectedUnit.dictionaryName;
  }
};
//添加修改
const submitAddOrEdit = async (info) => {
  operate.addLoading = true;
  let msg =
    operate.openKey == "edit"
      ? `${t("assetsList.title")}:${info.assetsName}${t("message.editSuccess")}`
      : `${t("assetsList.title")}:${info.assetsName}${t("message.addSuccess")}`;
  // 获取用户信息，避免重复解析
  const userInfo = JSON.parse(getUserInfo());

  // 组装请求参数
  const params = {
    ...info,
    ...(operate.openKey === "add"
      ? { createUserId: userInfo.userId, createUser: userInfo.userName }
      : { updateUserId: userInfo.userId, updateUser: userInfo.userName }),
  };

  try {
    await AddOrEditAssets(params).then((res) => {
      ElMessage({ message: msg, type: "success" });
    });
    await cancelAddOrEdit();
    await queryList();
  } catch (error) {
    operate.addLoading = false;
  }
};

const cancelAddOrEdit = (value) => {
  value = info;
  operate.open = false;
};

///高级搜索的
const searchDeptNodeClick = (node) => {
  searchConfig.value.form.useOrganizationId = node.value;
  queryAllUsers(searchConfig.value.form.useOrganizationId);
  proxy.$refs["rightToolRef"].$refs["AdvanceSearchRef"].$refs[
    "useOrganizationTreeSelect"
  ][0].blur();
};

const handleClearEnableFlag = (value) => {
  value ? value : (searchConfig.value.form.enableFlag = -1);
};
const searchConfig = ref({
  form: {
    ownershipOrganizationalId: "",
    enableFlag: -1,
    IsCheck: -1,
  },
  formItems: [
    {
      label: t("assetsList.assetStatus"),
      prop: "enableFlag",
      type: "el-select",
      attrs: {
        clearable: false,
        placeholder: t("assetsList.assetStatusPlaceholder"),
      },
      options: assetsStatus,
      optionProps: {
        key: "id",
        label: "name",
        value: "id",
      },
      events: {
        clear: handleClearEnableFlag,
      },
    },
    {
      label: t("assetsList.assetType"),
      prop: "assetsClassifyId",
      type: "el-select",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetTypePlaceholder"),
      },
      options: AssetClassification,
      optionProps: {
        key: "dictionaryKey",
        label: "dictionaryName",
        value: "dictionaryCode",
      },
      events: {},
    },
    {
      label: t("assetsList.organization"),
      prop: "ownershipOrganizationalId",
      type: "el-tree-select",
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        placeholder: t("assetsList.orgPlaceholder"),
      },
      options: depts,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {},
    },
    {
      label: t("assetsList.area"),
      prop: "regionId",
      type: "el-tree-select",
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        placeholder: t("assetsList.regionPlaceholder"),
      },
      options: GeographicRegion,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {},
    },

    {
      label: t("assetsList.assetCode"),
      prop: "assetsCode",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetCodePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetName"),
      prop: "assetsName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetNamePlaceholder"),
      },
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.userInputPlaceholder"),
      },
    },
    {
      label: t("assetsList.model"),
      prop: "specModel",
      type: "el-input",
      attrs: { clearable: true, placeholder: t("assetsList.modelPlaceholder") },
    },
  ],
  rules: {},
});

const handleSearch = async (info) => {
  searchConfig.value.form.IsCheck = -1;
  info.IsCheck = -1;
  await queryList();
};

queryList();
queryOrganization();
</script>
<style lang="scss" scoped></style>
